const originalOpen = XMLHttpRequest.prototype.open;
const originalSend = XMLHttpRequest.prototype.send;

XMLHttpRequest.prototype.open = function(method, url) {
    this._url = url;
    originalOpen.apply(this, arguments);
};

XMLHttpRequest.prototype.send = function(body) {
    const oldOnLoad = this.onload;

    this.onload = function() {
        if (this._url.includes('https://prod.rtymgt.com/api/v4/respondents/search')) {
            try {
                let response = JSON.parse(this.responseText);

                // 修改 Respondent 信息
                if (response.Respondent) {
                    response.Respondent.threat_potential = "low";
                    response.Respondent.threat_potential_score = 15;
                    response.Respondent.respondent_risk = 0;
                }

                // 修改 Surveys 信息
                if (response.Surveys && response.Surveys.length > 0) {
                    response.Surveys[0].duplicate_score = 0;
                    response.Surveys[0].duplicate_potential = "low";
                    response.Surveys[0].failure_reason = "0";
                }

                // 让 responseText 可修改
                const modifiedResponse = JSON.stringify(response);
                Object.defineProperty(this, 'response', { value: modifiedResponse, configurable: true });
                Object.defineProperty(this, 'responseText', { value: modifiedResponse, configurable: true });

            } catch (e) {
                console.error('Failed to parse or modify response', e);
            }
        }

        if (oldOnLoad) {
            oldOnLoad.apply(this, arguments);
        }
    };

    originalSend.call(this, body); // 使用修改后的 body 发送请求
};

console.log("XHR beasurveytaker interceptor installed");


function GetTokenURL(respondentID,uiid,tokenAPIKey,tokenAPIUrl) {
  var tokenUrl = tokenAPIUrl+ tokenAPIKey +"?tokens=1&rt_sr_pd="+respondentID+"&rt_hd_el="+crypto.randomUUID();
    var tokenResponse= CallAPI(tokenUrl,"GET",null);
        const tokenJSON = JSON.parse(tokenResponse);
        return tokenJSON.results[0].token;
    }
    function CallSearch(tokenID,searchUrlAPI) {

       //var searchUrlAPI = searchAPIUrl+searchApiKey+"?sn_ud="+uiid+"&sy_nr="+surveyID+"&rt_sr_pd="+respondentID+"&coordinates=1&df_details=1&usage_type=1&vpt=check&wd=1&set_window=1&sy_sy_te_id=0&pm_sr_id="+supplierID + "&rt_cy_ce="+countryCode;
        var searchResults=CallAPI(searchUrlAPI,'GET',null,tokenID);
        const searchResultsJSON = JSON.parse(searchResults);
        return searchResultsJSON;
    }
    function CallAPI(url, callType, reqBody, headerToken ) {
        var xhttp = new XMLHttpRequest();
        xhttp.onreadystatechange = function() {
            if (this.readyState == 4 && this.status == 200) {
                return (this.responseText);
            } else {
                return "ERROR";
            }
        };
        xhttp.open(callType, url, false);
        xhttp.withCredentials = true;
        xhttp.setRequestHeader("Content-type", "application/json");
        if(headerToken!=null)
            xhttp.setRequestHeader("token",headerToken)
        if(reqBody !=null){
            xhttp.send(reqBody);
        }
        else{
            xhttp.send();
        }
        return xhttp.responseText;
    }
